<?php

class Model_Listing_Residential extends Model_Listing implements Model_Listing_Interface
{
    const BATHROOM_MIN = 0;
    const BATHROOM_MAX = 10;
    const SIZE_MIN = 0;
    const SIZE_MAX = 5000;
    const BUILDING_AGE_MIN = 0;
    const BUILDING_AGE_MAX = 40;
    const MANAGEMENT_FEE_MIN = 0;
    const MANAGEMENT_FEE_MAX = 150000;
    const GOVERNMENT_FEE_MIN = 0;
    const GOVERNMENT_FEE_MAX = 150000;

    protected static  $_collection = 'listing';

    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
        'fac'  => array('Array'), //facilities
        'vie'  => array('Array'), //view
        'roo'  => array('Array'), //rooms
        'out'  => array('Array'), //outdoor
        'lay'  => array('Array'), //layout
        'con'  => array('Array'), //conditions
        'dir'  => array('Array'), //direction
    );

    protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
            'br'  => 'bedroom',
            'ao'  => 'agency_owner',
            'soa' => 'sole_agency',
            'an'  => 'agent_name',
            'ai'  => 'agent_id',
            'ap'  => 'agent_phone',
            'ae'  => 'agent_email',
            'sp'  => 'sale_price',
            'pn'  => 'price_negotiable',
            'sl'  => 'sell_lease',
            'led' => 'lease_enddate',
            'clp' => 'current_lease_price',
            'rp'  => 'rent_price',
            'rmf' => 'rent_include_mngt_fee',
            'sz'  => 'size',
            'ba'  => 'bathroom',
            'bla' => 'building_age',
            'blt' => 'building_type',
            'fz'  => 'floor_zone',
            'mf'  => 'management_fee',
            'gf'  => 'government_fee',
            'arl1'  => 'area_l1',
            'arl2'  => 'area_l2',
            'fac'  => 'facilities',
            'vie'  => 'views',
            'roo'  => 'rooms',
            'out'  => 'outdoor',
            'con'  => 'conditions',
            'lay'  => 'layout',
            'oth'  => 'other',
			'oth_en'  => 'other_en',
			'oth_tc'  => 'other_tc',
			'rt'  => 'rent_type',
			'oth_rm'  => 'other_room',
			'to'  => 'toilet',
			'wc_flr'  => 'which_floor',
			'to_flr'  => 'total_floor',
			'age'  => 'age',
			'tsz'  => 'total_size',
			'dir'  => 'direction',
			'ren'  => 'renovation',
			'cpx'  => 'complex',
        ), static::$_transcript);
        if (empty($config['documentClass'])) {
            $config['documentClass'] = 'Model_Listing_Residential';
        }
        parent::__construct($data, $config);
    }
	public static function getTranslationFormField()
    {
        $arr = array(
			'tl_en' =>'text',
			'cs_en' =>'textarea',
			'oth_en' =>'text'
		);
		
		return $arr;
    }
    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
        return new Listing_Form_PostAnAddResidentialForm($options);
    }

    public function getAdDetailPartialName()
    {
        return 'customization/residential.phtml';
    }

    public function getAdPreviewPartialName()
    {
        return $this->getAdDetailPartialName();
    }


    public static function getSearchResultPartialName()
    {
        return 'residential';
    }
    public static function getRefineSearchForm()
    {
        return new Search_Form_ResidentialRefineForm();
    }

    public static function processRefineSearchForm(&$get, $page, $per_page, &$query, &$fields, &$additionalParameters)
    {

        //echo '<pre>';print_r($_GET);exit;

        //$q       = isset($_GET['keyword']) ? strtolower($_GET['keyword']) : false;
        $results = false;
        if(empty($fields)) {
            $fields  = array('description', 'title', 'area_l2_name', 'area_l1_name', 'street');
        }
        if(empty($additionalParameters)) {
            $additionalParameters = array();
        }
        $values  = array();
        //$get     = $_GET;
/*
        if (!empty($get['keyword'])) {
            $values['description'] = ' '.strtolower($get['keyword']).' ';
            $values['title']       = ' '.strtolower($get['keyword']).' ';
            
            //find the bedroom
            $pattern = '#(?<=([0-9]\s))bedroom#iu';
            if (preg_match($pattern, strtolower($get['keyword']), $match)) {
                $values['bedroom'] =  '"'.$match[1].'"';
            }
        }
*/
        
//s=defined search terms based on all verticals
        $search_terms = self::getSearchTextTerms();
        
        $exact_search_terms = self::getExactSeachTerms();
        
        $q      = '';
        $qq     = !empty($_GET['keyword']) ? $_GET['keyword'] : '';
        $to_add = ' ';

        //add the username
        if (!empty($get['keyword'])) {
            //$q = '(username_lower:"'.$get['keyword'].'"^50.0) ';
        }

        if (!empty($exact_search_terms)) {
            foreach($exact_search_terms as $name => $val) {
                foreach($val as $k => $v) {
                    if (preg_match('#('.$v.')#i', $get['keyword'], $match)) {
                        //var_dump($match, $v, $get['keyword'], str_ireplace( $v, '', $get['keyword']));
                        $get['keyword'] = str_ireplace( $v, '', $get['keyword']);
                        $q .= $to_add.str_replace('_name', '', $name) .':'.$k.'^5.0 ';
                        $to_add = ' OR ';
                    }
                }
            }
            if (!empty($q) && !empty($tmp)) {
                $q = ' OR ('.$tmp.') ';
            }
        }
        
        $pattern = '#(?<=([0-9]))\s+bedroom[s]?#iu';
        if (preg_match($pattern, strtolower($get['keyword']), $match)) {
            $qq = str_ireplace($match[1].$match[0], '"'.$match[1].$match[0].'"', $qq);
            $get['keyword'] = str_ireplace($match[1].$match[0], '', $get['keyword']);
            $tmp = ' bedroom:'.trim($match[1]).'^9.0 ';
            if (!empty($q)) {
                $q .= ' OR ('.$tmp.') ';
            } else {
                $q = $tmp;
            }
        }
        
        $to_add = ' ';
        
        //remove quoted words and add them to q
        $bak = $get['keyword'];
        
        
        $arr = preg_match_all('#\"(.*?)\"#i', $get['keyword'], $match);
        foreach ($match[1] as $v) {
            $q .= ' AND "'.$v.'"';
        }
        $get['keyword'] = preg_replace('#"(.*?)"#i', '', $get['keyword']);
        $qf = '';
        foreach($search_terms as $v => $weight) {
            $qf .= $v.'^'.$weight.' ';
        }
        
        if (!empty($qf)) {
            $additionalParameters['qf'] = $qf;
        }
        if (!empty($qq)) {
            $additionalParameters['qq']   = $qq;
        }  
        
        $get['keyword'] = trim($get['keyword']);
        if (!empty($get['keyword'])) {
            if (!empty($q)) {
                $q.=' OR ';
            }
            $q .='(';
            foreach ($fields as $f) {
                $list = explode(' ', trim($get['keyword']));
                foreach($list as $vl) {
                    if (!empty($vl)) {
                        $q .= $to_add.''.$f.':'.$vl;
                        $to_add = ' OR ';
                    }
                }
            }
            $q.=') ';
        }
        
        
        $q.= ' OR _query_:"{!dismax qf=$qf v=$qq}" ';
        
        if (empty($_GET['keyword'])) {
            $q = '*:*';
        }
        
        /*
       // echo '<pre>';print_r($values);
        foreach($values as $k => $val) {
            if (is_array($val)) {
                $tmp = array();
                foreach($val as $k2 => $v2) {
                    $tmp[] = ' '.$k.':'.$v2;
                }
                $values[$k] = '('.implode(' OR ', $tmp).')';
            } else {
                $values[$k] = ' '.$k.':'.$val;
            }
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        } else {
            $query = '*:*';
        }
        */
        $query = $q;
        
        $get['sort'] = empty($get['sort']) ? '' : $get['sort'];

        switch ($get['sort']) {
            case 'highest':
                $get['sort'] = 'highest';
                $sort = 'price desc';
                break;
            case 'lowest':
                $get['sort'] = 'lowest';
                $sort = 'is_free asc, price asc';
                break;
            case 'rel':
                $get['sort'] = 'rel';
                $sort = 'score desc';
                break;
            case 'recent':
                $get['sort'] = 'recent';
                $sort = 'posted_at desc';
                break;
            case 'status':
                $get['sort'] = 'status';
                $sort = 'status desc';
                break;
            default:
                if (!empty($get['keyword'])) {
                    $get['sort'] = 'rel';
                    $sort         = 'score desc';
                } else {
                    $get['sort'] = 'recent';
                    $sort         = 'posted_at desc';
                }
        }

        $additionalParameters['fl']   = '*,score';
        $additionalParameters['sort'] = $sort;
        
        
        $buy_rent = false;
        $fq = '';
        if(!empty($additionalParameters['fq'])) {
            $fq = $additionalParameters['fq'];
        }
        $valuesplus = array();

        if (!empty($get['has_image'])) {
            $valuesplus['has_image'] = true;
        }


        // Sale by
        if (!empty($get['wantto'])) {
            $buy_rent = $get['wantto'];            
        }
        elseif (!empty($get['want_to']['buy_rent'])) {
            $buy_rent = $get['want_to']['buy_rent'];
        }

        // Sale by
        if (!empty($buy_rent)) {
            if ($buy_rent == 'Buy') {
                //Sale Category
                $sales = array();
                $sale = Model_Category::one(array('id' => 'c554'));
                $sales1 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c414'));
                $sales2 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c438'));
                $sales3 = $sale->_id;
                $category = ' +(category:'.$sales1.' OR category:'.$sales2.' OR category:'.$sales3.') ';
            }
            elseif ($buy_rent == 'Rent') {
                $rents = array();
                $rent = Model_Category::one(array('id' => 'c553'));
                $rents1 = $rent->_id;
                $rent = Model_Category::one(array('id' => 'c413'));
                $rents2 = $rent->_id;
                $rent = Model_Category::one(array('id' => 'c432'));
                $rents3 = $rent->_id;
                $category = ' +(category:'.$rents1.' OR category:'.$rents2.' OR category:'.$rents3.') ';
            }
        }

        // Type
        if (!empty($get['type'])) {
            $valuesplus['property_type'] = $get['type'];
        }

        // Sale by
        if (!empty($get['agency_owner'])) {
            $agency_owner = $get['agency_owner'];
        }
        elseif (!empty($get['seller']['saleby'])) {
            $agency_owner = $get['seller']['saleby'];
        }

        if (!empty($agency_owner)) {
            if ($agency_owner == 'Agency') {
                $valuesplus['agency_owner'] = '1';
            }
            elseif ($agency_owner == 'Owner') {
                $valuesplus['agency_owner'] = '0';
            }
        }

        //force only residential
        //$valuesplus['type_obj_s'] = 'Model_Listing_Residential';
        if(strpos($fq, '+type_obj_s') === false) {
            $valuesplus['type_obj_s'] = 'Model_Listing';
        }
        
        //$valuesplus['type_obj'] = new MongoId("4cda3e818835c16810000000");

        

        
        //Price (Sale/Buy)
        if (isset($get['price']) && isset($get['price-1'])) {
            $price  = $get['price'];
            $price1 = $get['price-1'];
        }

        if (isset($price) && isset($price1)) {
            $test1 = false;$test2 = false;
            if (empty($price1)) {
                $price1 = '*';
                $test1 = true;
            }
            if (empty($price)) {
                $price = '0';
                $test2 = true;
            }

            if (!$test1 || !$test2) {
                // Check if this is to rent or to buy
                if ($buy_rent === 'Rent') {
                    $valuesplus['rent_price'] = '['.intval(str_replace(",","",$price)).' TO '.str_replace(',', '', $price1).']';
                } elseif ($buy_rent === 'Buy') {
                    $valuesplus['sale_price'] = '['.intval(str_replace(",","",$price)).' TO '.str_replace(',', '', $price1).']';
                } else {
                    $valuesplus['price'] = '['.intval(str_replace(",","",$price)).' TO '.str_replace(',', '', $price1).']';
                    //$valuesplus['sale_price'] = '['.$price.' TO '.$price1.']';
                }
            }
        }

        // Area
        if (!empty($get['area_l1'])) {
            $valuesplus['area_l1'] = $get['area_l1'];
        }

        // District
        if (!empty($get['area_l2'])) {
            $valuesplus['area_l2'] = $get['area_l2'];
        }

        if (!empty($get['city'])) {
            $valuesplus['city'] = (int) $_GET['city'];
        }


        // Includes management and government fees
        if (!empty($get['want_to']['buy_rent'])) {
            if ((!empty($get['optional']['includes_fees'])) & ($get['want_to']['buy_rent'] == 'Rent')){
                $valuesplus['rent_include_mngt_fee'] = $get['optional']['includes_fees'];
            }
        }

        // Management Fee and government Fee
        if (!empty($get['want_to']['buy_rent'])) {
            if ($get['want_to']['buy_rent'] == 'Rent') {
                if (isset($get['optional-management_fee']) && isset($get['optional-management_fee-1'])) {
                    $test1 = false;$test2 = false;
                    if ($get['optional-management_fee-1'] == Model_Listing_Residential::MANAGEMENT_FEE_MAX) {
                        $get['optional-management_fee-1'] = '*';
                        $test1 = true;
                    }
                    if ($get['optional-management_fee'] == Model_Listing_Residential::MANAGEMENT_FEE_MIN) {
                        $get['optional-management_fee'] = '0';
                        $test2 = true;
                    }
                    if (!$test1 || !$test2) {
                       $valuesplus['management_fee'] = '['.$get['optional-management_fee'].' TO '.$get['optional-management_fee-1'].']';
                    }
                }
                if (isset($get['optional-government_fee']) && isset($get['optional-government_fee-1'])) {
                    $test1 = false;$test2 = false;
                    if ($get['optional-government_fee-1'] == Model_Listing_Residential::GOVERNMENT_FEE_MAX) {
                        $get['optional-government_fee-1'] = '*';
                        $test1 = true;
                    }
                    if ($get['optional-government_fee'] == Model_Listing_Residential::GOVERNMENT_FEE_MIN) {
                        $get['optional-government_fee'] = '0';
                        $test2 = true;
                    }
                    if (!$test1 || !$test2) {
                       $valuesplus['government_fee'] = '['.$get['optional-government_fee'].' TO '.$get['optional-government_fee-1'].']';
                    }
                }
            }
        }

        // Buy with lease
        if (!empty($get['optional']['buy_with_lease'])) {
            $valuesplus['sell_lease'] = $get['optional']['buy_with_lease'];
        }
        // Price negotiable
        if (!empty($get['price_negotiable'])) {
            $valuesplus['price_negotiable'] = $get['price_negotiable'];
        }
        // Floor Zone
        if (!empty($get['floor_zone'])) {
            $valuesplus['floor_zone'] = $get['floor_zone'];
        }

        //Size
        if (isset($get['size']) && isset($get['size-1'])) {
            $size  = $get['size'];
            $size1 = $get['size-1'];
        }
        
        if (isset($size) && isset($size1)) {
            $test1 = false;$test2 = false;
            if ($size1 == Model_Listing_Residential::SIZE_MAX) {
                $size1 = '*';
                $test1 = true;
            }
            if ($size == Model_Listing_Residential::SIZE_MIN) {
                $size = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['size'] = '['.$size.' TO '.$size1.']';
            }
        }

        //Bedrooms
        // Floor Zone
        if (!empty($get['bedroom'])) {
            $valuesplus['bedroom'] = $get['bedroom'];
        }

        //Bathrooms
        if (isset($get['bathroom']) && isset($get['bathroom-1'])) {
            $test1 = false;$test2 = false;
            if ($get['bathroom-1'] == Model_Listing_Residential::BATHROOM_MAX) {
                $get['bathroom-1'] = '*';
                $test1 = true;
            }
            if ($get['bathroom'] == Model_Listing_Residential::BATHROOM_MIN) {
                $get['bathroom'] = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['bathroom'] = '['.$get['bathroom'].' TO '.$get['bathroom-1'].']';
            }
        }

        //Building Age
        if (isset($get['building_age']) && isset($get['building_age-1'])) {
            $building_age  = $get['building_age'];
            $building_age1 = $get['building_age-1'];
        }

        if (isset($building_age) && isset($building_age1)) {
            $test1 = false;$test2 = false;
            if ($building_age1 == Model_Listing_Residential::BUILDING_AGE_MAX) {
                $building_age1 = '*';
                $test1 = true;
            }
            if ($building_age == Model_Listing_Residential::BUILDING_AGE_MIN) {
                $building_age = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['building_age'] = '['.$building_age.' TO '.$building_age1.']';
            }
        }

        // Building Type
        if (!empty($get['building_type'])) {
            $valuesplus['building_type'] = $get['building_type'];
        }

        // Facilities
        if (!empty($get['optional']['facilities'])) {
            $valuesplus['facilities'] = $get['optional']['facilities'];
        }
        // View
        if (!empty($get['optional']['views'])) {
            $valuesplus['views'] = $get['optional']['views'];
        }
        // Rooms
        if (!empty($get['optional']['room'])) {
            $valuesplus['rooms'] = $get['optional']['room'];
        }
        // Outdoor
        if (!empty($get['optional']['outdoor'])) {
            $valuesplus['outdoor'] = $get['optional']['outdoor'];
        }
        // Layout
        if (!empty($get['optional']['layout'])) {
            $valuesplus['layout'] = $get['optional']['layout'];
        }
        // Conditions
        if (!empty($get['optional']['conditions'])) {
            $valuesplus['conditions'] = $get['optional']['conditions'];
        }

        // Building/Street Name
        if (!empty($get['street'])) {
            $valuesplus['street'] = ''.$get['street'].'';
        }

        foreach($valuesplus as $k => $val) {
          $valuesplus[$k] = '+'.$k.':'.$val.' ';
        }

        if (!empty($category)) {
            $fq .= $category;
        }

        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
        //echo '<PRE>';print_r($valuesplus);exit;
    }

    public static function getBuildingType($id = null)
    {
        $res = array('' => 'All') + self::getBuildingTypePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getBuildingTypePostAd()
    {
        return array(
            '' => 'Select',
            1 => 'Low Rise',
            2 => 'Middle Rise',
            3 => 'Highrise',
            4 => 'Estate/Complex',
            5 => 'House/Villa',
            6 => 'Stand-alone Building',
            7 => 'Tenements/Walk-up',
            8 => 'Village House'
        );
    }

    public static function getFloorZone($id = null)
    {
        $res = array('' => 'All') + self::getFloorZonePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
        
    }

    public static function getFloorZonePostAd()
    {
        return array(
            '' => 'Select',
            1 => 'Groung floor',
            2 => 'Low',
            3 => 'Medium',
            4 => 'High',
            5 => 'Very High'
        );
    }
    
    public static function getRenovationPostAd()
    {
        return array(
            '' => 'Select',
            1 => '毛坯',
            2 => '简单装修',
            3 => '中等装修',
            4 => '精装修',
            5 => '豪华装修'
        );
    }

    public static function getBedroom($id = null)
    {
        $res = array('' => 'All') + self::getBedroomPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getBedroomPostAd()
    {
        return array(
            '' => 'Select',
            99 => 'Studio',
            1 => Ac_Util::getChineseNumber('1'),
            2 => Ac_Util::getChineseNumber('2'),
            3 => Ac_Util::getChineseNumber('3'),
            4 => Ac_Util::getChineseNumber('4'),
            5 => Ac_Util::getChineseNumber('5'),
            /*6 => Ac_Util::getChineseNumber('6'),
            7 => Ac_Util::getChineseNumber('7'),
            8 => Ac_Util::getChineseNumber('8'),
            9 => Ac_Util::getChineseNumber('9'),*/
            98 => 'Other'
        );
    }
    
    public static function getToilet($id = null)
    {
        $res = array('' => 'All') + self::getToiletPostAd(); 
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getToiletPostAd()
    {
        return array(
            '' => 'Select',
  
            '1' => Ac_Util::getChineseNumber('1'),
            
            '2' => Ac_Util::getChineseNumber('2'),
            
            '3' => Ac_Util::getChineseNumber('3'),
            
            '4' => Ac_Util::getChineseNumber('4'),
            
            '5' => Ac_Util::getChineseNumber('5'),
        );
    }

    public static function getOtherRoom($id = null)
    {
        $res = array('' => 'All') + self::getOtherRoomPostAd();

        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getOtherRoomPostAd()
    {
        return array(
            '' => 'Select',
            1 => Ac_Util::getChineseNumber('1'),
            2 => Ac_Util::getChineseNumber('2'),
            3 => Ac_Util::getChineseNumber('3'),
            4 => Ac_Util::getChineseNumber('4'),
            5 => Ac_Util::getChineseNumber('5'),
            /*6 => Ac_Util::getChineseNumber('6'),
            7 => Ac_Util::getChineseNumber('7'),
            8 => Ac_Util::getChineseNumber('8'),
            9 => Ac_Util::getChineseNumber('9'),*/
            98 => 'Other'
        );
    }
    
    
    public static function getRentTypePostAd()
    {
        return array(
            '' => 'Select',
            '1' => '整套出租',
            '2' => '单间出租',
            '3' => '床位',
        );
    }

    public static function getBuildingAge($id = null)
    {
        $res = array('' => 'All') + self::getBuildingAgePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getBuildingAgePostAd()
    {
        $array = array();
        $array[''] = 'Select';
        for ($i=1;$i<=50;$i++)
        {
            $array[$i] = $i;
        }
        return $array;
    }


    public static function getFacilitiesSearch($id = null)
    {
        $res = array('' => 'All') + self::getFacilities();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }    
    
    public static function getFacilities()
    {
        return array(
            1 => 'Car Park',
            2 => 'Club House',
            3 => 'Disabled Access',
            4 => 'Elevator',
            5 => 'Gym',
            6 => 'Playground',
            7 => 'Shuttle Bus',
            8 => 'Swimming Pool',
            9 => 'Security',
            10 => 'Tennis Court'
        );
    }
	
	public static function getDirections()
    {
        return array(
            1 => '东',
            2 => '南',
            3 => '西',
            4 => '北',
            5 => '东南',
            6 => '西南',
            7 => '东北',
            8 => '西北',
        );
    }
    
    public static function getFacilitiesValues($id = null)
    {
        $res = array(
            1 => array('Car Park', 'parking','carpark'),
            2 => array('Club House', 'clucbhouse'),
            3 => 'Disabled Access',
            4 => array('Elevator', 'lift'),
            5 => array('Gym', 'fitness'),
            6 => 'Playground',
            7 => 'Shuttle Bus',
            8 => array('Swimming Pool', 'Pool'),
            9 => 'Security',
            10 => 'Tennis Court'
        );
        if ($id !== null) {
            return $res[(int)$id];
        }
        return $res;        
    }
    

    public static function getViewsSearch($id = null)
    {
        $res = array('' => 'All') + self::getViews();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }
    
    public static function getViews()
    {
        return array(
            1 => 'City',
            2 => 'Green/Mountain',
            3 => 'Harbour/Sea',
            4 => 'Open',
            5 => 'Race Course'
        );
    }

    public static function getViewsValues($id = null)
    {
        $res = array(
            1 => array('City', 'cityview'),
            2 => array('Green/Mountain', 'green view','mountain view'),
            3 => array('Harbour/Sea', 'seaview','sea view','harbour view'),
            4 => array('Open', 'open view'),
            5 => 'Race Course'
        );
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;        
    }
    
    
    public static function getRoomsSearch($id = null)
    {
        $res = array('' => 'All') + self::getRooms();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }
    
    public static function getRooms()
    {
        return array(
            1 => 'Ensuites',
            2 => 'Dining Room',
            3 => 'Family Room',
            4 => 'Living Room',
            5 => 'MaidÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢s Room'
        );
    }

    public static function getOutdoorSearch($id = null)
    {
        $res = array('' => 'All') + self::getOutdoor();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }
    
    public static function getOutdoor()
    {
        return array(
            1 => 'Balcony',
            2 => 'Barbecue',
            3 => 'Garden',
            4 => 'Roof Top',
            5 => 'Terrace/Patio'
        );
    }

    public static function getLayoutSearch($id = null)
    {
        $res = array('' => 'All') + self::getLayout();
        
        if ($id !== null) {
            if (!empty($res[$id])) {
                return $res[$id];
            } else {
                return null;
            }
        }
        return $res;
    }

    public static function getLayout()
    {
        return array(
            1 => 'Duplex',
            2 => 'Penthouse',
            3 => 'Simplex',
            4 => 'Triplex'
        );
    }

    public static function getConditionsSearch($id = null)
    {
        $res = array('' => 'All') + self::getConditions();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getConditions()
    {
        return array(
            1 => 'Furnished',
            2 => 'Non-Furnished',
            3 => 'Fully Renovated',
            4 => 'Non-Renovated'
        );
    }

    public static function getSearchTextTerms() 
    {
        return array(
            'description' => '1.0', 
            'title_lang' => '7.0', 
            'bedroom' => '9.0', 
            'area_l2_name' => '9.0',
            'street' => '7.0',
            'floor_zone_name' => '5.0',
            'safetyfeatures_name' => '5.0',
            'facilities_name' => '5.0',
            'building_type_name' => '5.0',            
            'property_views_name' => '5.0',
            'rooms_name' => '5.0',
            'outdoor_name' => '5.0',
            'layout_name' => '5.0',
            'conditions_name' => '5.0',
            
        );
    }    
    
    /*
     * return a list of all the possible values that should be extracted from the keyword search and be specified as exact term
     * 
     */
    public static function getExactSeachTerms() 
    {
       return array(
                'building_type_name'  => self::getBuildingType(),
                'conditions_name'     => self::getConditions() ,
                'facilities_name'     => self::getFacilitiesValues(),
                'floor_zone_name'     => self::getFloorZone(),
                'layout_name'         => self::getLayout(),
                'outdoor_name'        => self::getOutdoor(),
                'rooms_name'          => self::getRooms(),
                'property_views_name' => self::getViewsValues(),
           );
    }
    
    public function getSolrDocument($document = null)
    {
        if (!$document instanceof Apache_Solr_Document) {
            $document = new Apache_Solr_Document();
        }
        $view = Zend_Registry::get('Zend_View');
        //Residential
        
        $document->bedroom                  = (int)$this->br;
        
        if (!empty($this->ao)) {
            $document->agency_owner             = (string)$this->ao;
        }
        
        
        if (!empty($this->ty)) {
            foreach ((array)$this->ty as $data) {
                $document->addField('property_type', (int)$data);
                $document->addField('property_type_name', self::getPropertyType($data));
                $document->addField('property_type_name', $view->t(self::getPropertyType($data), Model_Translate::TC));
            }
        }
        
        //$document->sole_agency              = (int)$this->soa;
        
        //$document->agent_name               = (string)$this->an;
        //$document->agent_id                 = (int)$this->ai;
        
        //$document->agent_phone              = (int)$this->ap;
        //$document->agent_email              = (string)$this->ae;
        
        //$document->price_negotiable         = (int)$this->pn;
        $document->sale_lease               = (string)$this->sl;
        $document->lease_enddate            = (string)$this->led;
        $document->current_lease_price      = (string)$this->clp;
        $document->rent_include_mngt_fee    = (string)$this->rmf;
        
        $document->size                     = (int)$this->sz;
        $document->bathroom                 = (int)$this->ba;
        $document->building_age             = (int)$this->bla;
        
        $document->management_fee           = (int)$this->mf;
        $document->government_fee           = (int)$this->gf;


        if (!empty($this->sp)) {
            $document->sale_price = (int) $this->sp;
        }
        if(!empty($this->rp)) {
            $document->rent_price = (int) $this->rp;
        }
        
        
        if (!empty($this->blt)) {
            $document->building_type        = (string)$this->blt;
            $document->addField('building_type_name', self::getBuildingType($this->blt));
            $document->addField('building_type_name', $view->t(self::getBuildingType($this->blt), Model_Translate::TC));
        }
        if (!empty($this->fz)) {
            $document->floor_zone        = (string)$this->fz;
            $document->addField('floor_zone_name', self::getFloorZone($this->fz));
            $document->addField('floor_zone_name', $view->t(self::getFloorZone($this->fz), Model_Translate::TC));
        }

        //$document->other                    = (string)$this->oth;
        
        if (!empty($this->fac)) {
            foreach ((array)$this->fac as $data) {
                
                $document->addField('facilities', (string) $data);
                
                foreach((array)self::getFacilitiesValues($data) as $val) {
                    $document->addField('facilities_name', $val);
                    $document->addField('facilities_name', $view->t($val, Model_Translate::TC));
                }
            }
        }

        if (!empty($this->vie)) {
            foreach ((array)$this->vie as $data) {
                $document->addField('property_views', (string)$data);
                foreach((array)self::getViewsValues($data) as $val) {
                    $document->addField('property_views_name', $val);
                    $document->addField('property_views_name', $view->t($val, Model_Translate::TC));
                }                
            }
        }
        
        if (!empty($this->roo)) {
            foreach ((array)$this->roo as $data) {
                $document->addField('rooms', (string)$data);
                $document->addField('rooms_name', self::getRoomsSearch($data));
                $document->addField('rooms_name', $view->t(self::getRoomsSearch($data), Model_Translate::TC));
            }
        }
        
        if (!empty($this->lay)) {
            foreach ((array)$this->lay as $data) {
                $document->addField('layout', (string)$data);
                $document->addField('layout_name', self::getLayoutSearch($data));
                $document->addField('layout_name', $view->t(self::getLayoutSearch($data), Model_Translate::TC));
            }
        }
        if (!empty($this->out)) {
            foreach ((array)$this->out as $data) {
                $document->addField('outdoor', (string)$data);
                $document->addField('outdoor_name', self::getOutdoorSearch($data));
                $document->addField('outdoor_name', $view->t(self::getOutdoorSearch($data), Model_Translate::TC));
            }
        }
        if (!empty($this->vie)) {
            foreach ((array)$this->con as $data) {
                $document->addField('conditions', (string)$data);
                $document->addField('conditions_name', self::getConditionsSearch($data));
                $document->addField('conditions_name', $view->t(self::getConditionsSearch($data), Model_Translate::TC));
            }        
        }
        
        return parent::getSolrDocument($document);        
    }

    public function exportRest($compressed = false)
    {
        $res = parent::exportRest($compressed);
        $view = Zend_Registry::get('Zend_View');

        $res['type'] = 'residential';
        if ($compressed) {
            return $res;
        }
        $res['building'] = (string) $this->building;

        if ($this->bedroom>0) {
            $bedroom = self::getBedroom();
            if (in_array($this->bedroom, $bedroom)) {
                $res['bedrooms'] = (string) $this->bedroom;
                $res['bedrooms_en'] = (string) $bedroom[$this->bedroom];
                $res['bedrooms_tc'] = (string) $view->t($bedroom[$this->bedroom],  Model_Translate::TC);
            }
        }

        //$res['size'] = (string) $this->size;

        $res['sale_price'] = !empty($this->sale_price) ? (string)$this->sale_price :'';
        $res['rent_price'] = !empty($this->rent_price) ? (string)$this->rent_price :'';

        if (!empty($this->ty)) {
            foreach ((array)$this->ty as $data) {
                $res['property_type'] = (string)$data;
                $res['property_type_en'] = self::getPropertyType($data);
                $res['property_type_tc'] = $view->t(self::getPropertyType($data), Model_Translate::TC);
            }
        }
                
        $res['price_negotiable']         = !empty($this->pn) ? '1' : '0';
        $res['sale_lease']               = (string)$this->sl;
        $res['lease_enddate']            = (string)$this->led;
        $res['current_lease_price']      = (string)$this->clp;
        $res['rent_include_mngt_fee']    = (string)$this->rmf;
        
        $res['size']                     = (string)$this->size;
        $res['bathroom']                 = (string)$this->ba;
        
        $res['building_age']             = (string)$this->bla;
        
        $res['management_fee']           = (string)$this->mf;
        $res['government_fee']           = (string)$this->gf;
        
        
        if (!empty($this->blt)) {
            $res['building_type']        = (string)$this->blt;
            $res['building_type_en'] = self::getBuildingType($this->blt);
            $res['building_type_tc'] = $view->t(self::getBuildingType($this->blt), Model_Translate::TC);
        }
        if (!empty($this->fz)) {
            $res['floor_zone']    = (string)$this->fz;
            $res['floor_zone_en'] = self::getFloorZone($this->fz);
            $res['floor_zone_tc'] = $view->t(self::getFloorZone($this->fz), Model_Translate::TC);
        }

        if (!empty($this->fac)) {
            foreach ((array)$this->fac as $data) {
                $i = 0;
                foreach((array)self::getFacilitiesValues($data) as $val) {
                    $res['facilities'][$i]    = (string) $data;
                    $res['facilities_en'][$i] = $val;
                    $res['facilities_tc'][$i] = $view->t($val, Model_Translate::TC);
                    $i++;
                }
            }
        }

        if (!empty($this->vie)) {
            foreach ((array)$this->vie as $data) {
                $i = 0;            
                foreach((array)self::getViewsValues($data) as $val) {
                    $res['property_views'][$i]    = (string)$data;
                    $res['property_views_en'][$i] = $val;
                    $res['property_views_tc'][$i] = $view->t($val, Model_Translate::TC);
                }                
            }
        }
/*
        if (!empty($this->roo)) {
            foreach ((array)$this->roo as $data) {
                $res['bedrooms']    = (string)$data;
                $res['bedrooms_en'] = self::getRoomsSearch($data);
                $res['bedrooms_tc'] = $view->t(self::getRoomsSearch($data), Model_Translate::TC);
            }
        }
*/      
        if (!empty($this->lay)) {
            foreach ((array)$this->lay as $data) {
                $res['layout']    = (string)$data;
                $res['layout_en'] = self::getLayoutSearch($data);
                $res['layout_tc'] = $view->t(self::getLayoutSearch($data), Model_Translate::TC);
            }
        }
        if (!empty($this->out)) {
            foreach ((array)$this->out as $data) {
                $res['outdoor']    = (string)$data;
                $res['outdoor_en'] = self::getOutdoorSearch($data);
                $res['outdoor_tc'] = $view->t(self::getOutdoorSearch($data), Model_Translate::TC);
            }
        }
        if (!empty($this->vie)) {
            foreach ((array)$this->con as $data) {
                $res['conditions']    = (string)$data;
                $res['conditions_en'] = self::getConditionsSearch($data);
                $res['conditions_tc'] = $view->t(self::getConditionsSearch($data), Model_Translate::TC);
            }        
        }        
        
        $prices = array();              
        if (!empty($res['sale_price'])) {
            $prices[] = intval($res['sale_price']);
        } else {
            $prices[] = ' - ';
        }
        if (!empty($res['rent_price'])) {
            $prices[] = intval($res['rent_price']);
        } else {
            $prices[] = ' - ';
        }
        if (!empty($prices)) {
            //$res['price'] = implode(' / ', $prices);
        }
        if (empty($res['price'])) {
            if($this->is_free) {
                $price = $view->t('Free');
            }
            if (empty($price)) {
                $price = $view->t('Please contact');
            }
        }

        $res['price'] = '';
        

        
        return $res;
    }

    public function processRestForm()
    {
        $post = $_POST;

        if (!empty($_POST['building'])) {
            //$this->location = Model_Location::getDistrictId($_POST['district']);
        }

        //Bedroom
        if (!empty($_POST['bedroom']) && !in_array($_POST['bedroom'],array_keys(self::getBedroom()))) {
            throw new Ac_Exception_MissingInformation('Invalid value for Bedroom');
        }

        if (!empty($_POST['bedroom'])) {
            $this->bedroom = intval($_POST['bedroom']);
        }

        //Bathroom
        if (!empty($_POST['bathroom']) && !in_array($_POST['bathroom'],array_keys(self::getToilet()))) {
            throw new Ac_Exception_MissingInformation('Invalid value for Bathroom');
        }

        if (!empty($_POST['bathroom'])) {
            $this->bathroom = intval($_POST['bathroom']);
        }

        //Other room
        if (!empty($_POST['other_room']) && !in_array($_POST['other_room'],array_keys(self::getOtherRoom()))) {
            throw new Ac_Exception_MissingInformation('Invalid value for Other Room');
        }

        if (!empty($_POST['other_room'])) {
            $this->other_room = intval($_POST['other_room']);
        }

        //Direction
        $values = self::getDirection();
        $key    = $_POST['direction'];
        if (!empty($key) &&
                empty($values[$key]) && array_search($key, $values) === false) {
            throw new Ac_Exception_MissingInformation('Direction is empty');
        }
        if (!empty($values[$key])) {
            $this->direction = array(intval($key));
        } elseif(($res = array_search($key, $values)) !== false) {
            if (!is_null($res)) {
                $this->direction = array($res);
            }
        }

        //Renovation
        $values = self::getRenovationPostAd();
        $key    = $_POST['renovation'];
        if (!empty($key) &&
                empty($values[$key]) && array_search($key, $values) === false) {
            throw new Ac_Exception_MissingInformation('Renovation is empty');
        }
        if (!empty($values[$key])) {
            $this->renovation = intval($key);
        } elseif(($res = array_search($key, $values)) !== false) {
            $this->renovation = intval($res);
        }
/*        
        if (!empty($_POST['renovation']) && false === array_search($_POST['renovation'], self::getRenovationPostAd())) {
            throw new Ac_Exception_MissingInformation('Invalid value for Other Room');
        }

        if (!empty($_POST['renovation'])) {
            $this->renovation = (int) array_search($_POST['renovation'], self::getRenovationPostAd());
        }
  */      

        //Which floor
        if (!empty($_POST['floor']) && intval($_POST['floor']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for floor');
        }
        if (!empty($_POST['floor'])) {
            $this->which_floor = intval($_POST['floor']);
        }

        //Total floor
        if (!empty($_POST['total_floor']) && intval($_POST['total_floor']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for total floor');
        }
        if (!empty($_POST['total_floor'])) {
            $this->total_floor = intval($_POST['total_floor']);
        }

        //Age
        if (!empty($_POST['age']) && intval($_POST['age']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for age');
        }
        if (!empty($_POST['age'])) {
            $this->age = intval($_POST['age']);
        }
 

        //Size
        if (!empty($_POST['size']) && intval($_POST['size']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for size');
        }
        if (!empty($_POST['size'])) {
            $this->size = intval($_POST['size']);
        }
        

        //Sale price
        if (!empty($_POST['sale_price']) && intval($_POST['sale_price']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for sale price');
        }
        if(!empty($_POST['sale_price'])) {
            $this->sale_price = $_POST['sale_price'];
        }

        //Rent price
        if (!empty($_POST['rent_price']) && intval($_POST['rent_price']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for rent price');
        }
        if(!empty($_POST['rent_price'])) {
            $this->rent_price = $_POST['rent_price'];
        }



        parent::processRestForm();
        return true;
    }
}
